package net.xo68.destiny.manager.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.RespondResult;
import net.xo68.destiny.manager.dto.UserInfoDto;
import net.xo68.destiny.manager.dto.UserLoginDto;
import net.xo68.destiny.manager.dto.UserLoginResultDto;
import net.xo68.destiny.manager.security.SecurityUser;
import net.xo68.destiny.manager.security.UserJwtTokenTemplate;
import net.xo68.destiny.manager.service.SystemUserService;
import net.xo68.destiny.starter.manager.SchedulerManagerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@Api(value = "用户登录",tags = {"用户登录"})
@Slf4j
@RestController
public class UserLoginController {
    @Autowired
    private SchedulerManagerProperties schedulerManagerProperties;
    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserJwtTokenTemplate userJwtTokenTemplate;

    @ApiOperation(value="用户登录")
    @PostMapping("/login")
    public RespondResult<UserLoginResultDto> login(@Validated @RequestBody UserLoginDto userLoginDto, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return RespondResult.fail("用户名、密码不能为空",null);
        }
        SecurityUser securityUser= (SecurityUser) systemUserService.loadUserByUsername(userLoginDto.getAccount());
        if(securityUser==null){
            return RespondResult.fail("用户不存在;用户名或密码错误",null);
        }
        if(passwordEncoder.matches(userLoginDto.getRequired(),securityUser.getPassword())){
            UserLoginResultDto userLoginResult=UserLoginResultDto.of(securityUser,userJwtTokenTemplate.token(securityUser),schedulerManagerProperties.getUserTokenExpire().toMinutes()*60L);

            return RespondResult.ok("登录成功",userLoginResult);
        }else {
            return RespondResult.fail("用户名或密码错误",null);
        }
    }
    @ApiOperation(value="登录用户信息")
    @GetMapping("/userInfo")
    public RespondResult<UserInfoDto> userInfo(@ApiIgnore SecurityUser securityUser){

        return RespondResult.ok(UserInfoDto.of(securityUser));
    }
}
